package com.itboye.sunsun;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.itboye.sunsun.adapter.AnnoucementAdapter;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.NewsHotReaBean;
import com.itboye.sunsun.beans.NewsHotReaBean.AllData;
import com.itboye.sunsun.beans.NewsHotReaBean.AllData.AllList;
import com.itboye.sunsun.constants.NetPublicConstant;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.custome.XListView;
import com.itboye.sunsun.custome.XListView.IXListViewListener;
import com.itboye.sunsun.login.ui.LoginActivity;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseFragment;
import com.itboye.sunsun.utils.DebugLog;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.utils.XImageLoader;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsun.web.ui.WebActivity;

@SuppressLint("ValidFragment")
public class NoticeFragment extends BaseFragment implements IXListViewListener {

	private View noticeView;
	private Context context;
	private XListView lst_annoucement;
	WebView webview;
	String url;
	private int index = 6058;
	private int page = 1;
	private AllData arg0;
	private ArrayList<AllList> arrayList;

	public NoticeFragment() {

	}

	public NoticeFragment(Context context) {
		this.context = context;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// noticeView = inflater.inflate(R.layout.fragment_notice, container,
		// false);//以前版本
		noticeView = inflater.inflate(R.layout.activity_announcement, null);
		// url=NetPublicConstant.URL+"/APP_URL/Index/noticeBoard";
		// new Exception("安卓6.0 x86模拟器会导致崩溃").printStackTrace();
		return noticeView;
	}

	private Intent intent;
	private View headerView;
	private AnnoucementAdapter adapter;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		showProgressDialog("数据正在加载中，请稍后", true);
		headerView = LayoutInflater.from(getActivity()).inflate(
				R.layout.activity_announcement_headerview, null);
		lst_annoucement.addHeaderView(headerView);
		lst_annoucement.setPullLoadEnable(true);
		lst_annoucement.setXListViewListener(this);
		arrayList = new ArrayList<NewsHotReaBean.AllData.AllList>();
		adapter = new AnnoucementAdapter(arrayList, getActivity());

		lst_annoucement.setAdapter(adapter);
		getData(0);//公告消息
		getHeadChoujiangGonggao();//头部抽奖栏
		getHeadData();//抽奖结果栏
		headerView.findViewById(R.id.re_pingjiangjieguo).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						String uid = (String) SPUtils.get(App.ctx, null,
								SPContants.USER_ID, "");
						String password = (String) SPUtils.get(App.ctx, null,
								SPContants.PASSWORD, "");
						if (uid == null || uid == "") {
							intent = new Intent(context, LoginActivity.class);
						} else {
							intent = new Intent(context, WebActivity.class);
							intent.putExtra("title", "评奖结果");
							intent.putExtra("title2","论坛中奖名单贴榜");
							intent.putExtra("content","论坛中奖名单贴榜" );
							intent.putExtra("img", arrayList.get(0).getMainImg());
							intent.putExtra("url",
									NetPublicConstant.secondUrl+"/Webview/Post/viewPost?id="+arrayList.get(0).getId()+"&from=app");
						}
						startActivity(intent);
					}
				});
		headerView.findViewById(R.id.re_xingyunchongjiang).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						String uid = (String) SPUtils.get(App.ctx, null,
								SPContants.USER_ID, "");
						String password = (String) SPUtils.get(App.ctx, null,
								SPContants.PASSWORD, "");
						if (uid == null || uid == "") {
							intent = new Intent(context, LoginActivity.class);
						} else {
							intent = new Intent(context, WebActivity.class);
							intent.putExtra("title", "幸运抽奖");
							intent.putExtra("url",
									NetPublicConstant.secondUrl+"/Webview/Game/index?uid="
											+ uid + "&psw=" + password);
							intent.putExtra("title2","幸运抽奖");
							intent.putExtra("content","论坛中奖名单贴榜" );
							intent.putExtra("img", "SHARE_TO_QQ_IMAGE_URL");
						}
						startActivity(intent);
					}
				});
		lst_annoucement.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(getContext(), WebActivity.class);
				intent.putExtra("title", "公告详情");
				intent.putExtra("title2","公告详情");
				intent.putExtra("content", arrayList.get(position-2).getPostTitle());
				intent.putExtra("img", arrayList.get(position - 2).getMainImg());
				try {
					intent.putExtra("url",
							NetPublicConstant.secondUrl+"/Webview/Post/viewPost?id="
									+ arrayList.get(position - 2).getId()+"&from=app");
				} catch (Exception e) {
					intent.putExtra(
							"url",
							NetPublicConstant.secondUrl+"/Webview/Post/viewPost?id=" + 25);

				}
				startActivity(intent);
			}
		});
	}

	public void getHeadData() {
		MyJsonRequest<NewsHotReaBean.AllData> request = new MyJsonRequest.Builder<NewsHotReaBean.AllData>()
				.apiVer("100")
				.typeKey("BY_News_query")
				.param("position", "6059")
				.param("page_no", page)
				.requestListener(
						new XRequestListener<NewsHotReaBean.AllData>() {
							@Override
							public void onResponse(NewsHotReaBean.AllData arg0) {
								try {
									closeProgressDialog();
								} catch (Exception e) {
									// TODO: handle exception
								}
								if (arg0.getList().get(0).getStartTime() != null
										|| arg0.getList().get(0).getStartTime() != 0 + "") {
									((TextView) headerView
											.findViewById(R.id.time)).setText("时间："
											+ new SimpleDateFormat("yyyy.MM.dd")
													.format(Long.parseLong(arg0
															.getList().get(0)
															.getStartTime()) * 1000)
											+ "-"
											+ new SimpleDateFormat("yyyy.MM.dd")
													.format(Long.parseLong(arg0
															.getList().get(0)
															.getEndTime()) * 1000));
								}
								if (arg0.getList().get(0).getPostTitle() != null
										|| arg0.getList().get(0).getPostTitle() != "") {
									((TextView) headerView
											.findViewById(R.id.time_lottery_result))
											.setText(arg0.getList().get(0)
													.getPostTitle());
								}
								System.out.println("choujiangjieguo"+arg0.getList().get(0).getMainImg());
								if (arg0.getList().get(0).getMainImg() != null
										|| arg0.getList().get(0).getMainImg() != "") {
									XImageLoader
											.load(arg0.getList().get(0)
													.getMainImg(),
													(ImageView) headerView
															.findViewById(R.id.annoucement_img));
								}
								((ImageView) headerView
								.findViewById(R.id.annoucement_img)).setImageResource(R.drawable.defaultimage);
							}
						}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {

						stopRefresh();
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}
	
	public void getHeadChoujiangGonggao() {
		MyJsonRequest<NewsHotReaBean.AllData> request = new MyJsonRequest.Builder<NewsHotReaBean.AllData>()
				.apiVer("100")
				.typeKey("BY_News_query")
				.param("position", "6088")
				.param("page_no", page)
				.requestListener(
						new XRequestListener<NewsHotReaBean.AllData>() {
							@Override
							public void onResponse(NewsHotReaBean.AllData arg0) {
//								System.out.println(">>>>>>>>>>>>>>数据"
//										+ arg0.getList().size()
//										+ "<><>"
//										+ new SimpleDateFormat("yyyy.MM.dd")
//												.format(Long.parseLong(arg0
//														.getList().get(0)
//														.getStartTime()) * 1000));
//								// if (arg0 != null) {
//								// stopRefresh();
//								//
//								// arrayList.addAll(arg0.getList());
								if (arg0.getList().get(0).getStartTime() != null
										|| arg0.getList().get(0).getStartTime() != 0 + "") {
									((TextView) headerView
											.findViewById(R.id.lottory_time)).setText("时间："
											+ new SimpleDateFormat("yyyy.MM.dd")
													.format(Long.parseLong(arg0
															.getList().get(0)
															.getStartTime()) * 1000)
											+ "-"
											+ new SimpleDateFormat("yyyy.MM.dd")
													.format(Long.parseLong(arg0
															.getList().get(0)
															.getEndTime()) * 1000));
								}
								if (arg0.getList().get(0).getPostTitle() != null
										|| arg0.getList().get(0).getPostTitle() != "") {
									((TextView) headerView
											.findViewById(R.id.time_lottery))
											.setText(arg0.getList().get(0)
													.getPostTitle());
								}
								if (arg0.getList().get(0).getMainImg() != null
										|| arg0.getList().get(0).getMainImg() != "") {
									XImageLoader
											.load(arg0.getList().get(0)
													.getMainImg(),
													(ImageView) headerView
															.findViewById(R.id.lottory_img));
								}else{
									((ImageView) headerView
									.findViewById(R.id.lottory_img)).setImageResource(R.drawable.defaultimage);
								}
								// else {
								// headerView.findViewById(R.id.time_lottery_result).setVisibility(View.GONE);
								// }
								// // adapter.notifyDataSetChanged();
								// // com.itboye.sunsun.shop.ui ShopCarActivity
								//
								// } else {
								// //
								// txt_shownodata.setVisibility(View.VISIBLE);
								// }
							}
						}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {

						stopRefresh();
					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	public void getData(final int pullDown_pullUp) {
		// 6054
		if (pullDown_pullUp == 0) {// 上拉加载更多

		} else {// 下拉刷新
			page = 1;
		}
		MyJsonRequest<NewsHotReaBean.AllData> request = new MyJsonRequest.Builder<NewsHotReaBean.AllData>()
				.apiVer("100")
				.typeKey("BY_News_query")
				.param("position", index)
				.param("page_no", page)
				.requestListener(
						new XRequestListener<NewsHotReaBean.AllData>() {
							@Override
							public void onResponse(NewsHotReaBean.AllData arg0) {
								if (arg0 != null) {
									stopRefresh();
									if (pullDown_pullUp == 1)
										arrayList.clear();

									page++;
									arrayList.addAll(arg0.getList());
									// if (arg0.getList().get(1).getStartTime()
									// != null
									// || arg0.getList().get(1).getStartTime()
									// == 0 + "") {
									// ((TextView)
									// headerView.findViewById(R.id.time_lottery_result))
									// .setText("时间："+new
									// SimpleDateFormat("yyyy.MM.dd")
									// .format(Long.parseLong(arg0.getList().get(1).getStartTime())
									// * 1000)
									// + "-" + new
									// SimpleDateFormat("yyyy.MM.dd").format(
									// Long.parseLong(arg0.getList().get(1).getEndTime())
									// * 1000));
									// } else {
									// headerView.findViewById(R.id.time_lottery_result).setVisibility(View.GONE);
									// }
									adapter.notifyDataSetChanged();
									// com.itboye.sunsun.shop.ui ShopCarActivity

								} else {
									// txt_shownodata.setVisibility(View.VISIBLE);
								}
							}
						}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {

						stopRefresh();
					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	public void stopRefresh() {
		lst_annoucement.stopLoadMore();
		lst_annoucement.stopRefresh();
	}

	@Override
	public void onRefresh() {

		getData(1);
		getHeadChoujiangGonggao();
		getHeadData();
	}

	@Override
	public void onLoadMore() {
		getData(0);
	}
}
